package com.jhj.provider.resume.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.jhj.utils.StringUtil;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
import tk.mybatis.mapper.mapperhelper.EntityHelper;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;

import com.jhj.provider.resume.service.BaseService;

/**
 * 主要用途：通用Service 封装常用的CRUD方法
 */
public class BaseServiceImpl<T> implements BaseService<T> {

	private Logger logger = LoggerFactory.getLogger(Thread.currentThread().getStackTrace()[1].getClassName());

	@Autowired
	protected Mapper<T> mapper;// 泛型装配

	@Override
	public int deleteByPrimaryKey(Integer id) {
		return mapper.deleteByPrimaryKey(id);
	}

	@Override
	public int delete(T entity) {
		return mapper.delete(entity);
	}

	@Override
	public int insert(T entity) {
		return mapper.insertSelective(entity);
	}

	@Override
	public int update(T entity) {
		return mapper.updateByPrimaryKeySelective(entity);
	}

	@Override
	public T initPo(T entity) {

		Field[] fields = entity.getClass().getDeclaredFields();
		try {
			for (int i = 0; i < fields.length; i++) {
				String name = fields[i].getName(); // 获取属性的名字
				String type = fields[i].getGenericType().toString(); // 获取属性的类型
				Field fieldName = entity.getClass().getDeclaredField(name);
				fieldName.setAccessible(true);
				if (type.equals("class java.lang.String")) {
					fieldName.set(entity, "");
				}

				if (type.equals("class java.lang.Integer")) {
					fieldName.set(entity, 0);
				}

				if (type.equals("class java.lang.Short")) {
					fieldName.set(entity, (short) 0);
				}

				if (type.equals("class java.lang.Long")) {
					fieldName.set(entity, 0L);
				}

				if (type.equals("class java.lang.Double")) {
					fieldName.set(entity, 0);
				}

				if (type.equals("class java.lang.BigDecimal")) {
					fieldName.set(entity, BigDecimal.ZERO);
				}

				if (type.equals("class java.util.Date")) {
					fieldName.set(entity, new Date());
				}

			}
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return entity;
	}

	@Override
	public T selectByPrimaryKey(Integer id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public T selectOne(T entity) {
		return mapper.selectOne(entity);
	}

	/**
	 * 根据实体查询条件进行查询，注，仅支持mybatis实体的类，因为要查别名，比如addFrom ,要获取add_from
	 */
	@Override
	public List<T> selectBySearchVo(T entity, String orderBy) {
		Example example = this.bySearchVo(entity, orderBy);
		return mapper.selectByExample(example);
	}

	/**
	 * 根据实体查询条件进行查询,并分页，注，仅支持mybatis实体的类，因为要查别名，比如addFrom ,要获取add_from
	 */
	@SuppressWarnings({ "rawtypes" })
	@Override
	public PageInfo selectByListPage(T entity, int pageNo, int pageSize, String orderBy) {
		PageMethod.startPage(pageNo, pageSize);

		Example example = this.bySearchVo(entity, orderBy);

		List<T> list = mapper.selectByExample(example);
		PageInfo<T> pageInfo = new PageInfo<T>(list);
		return pageInfo;
	}

	private Example bySearchVo(T entity, String orderBy) {
		Example example = new Example(entity.getClass());

		Field[] fields = entity.getClass().getDeclaredFields();
		Criteria criteria = example.createCriteria();
		try {
			for (int i = 0; i < fields.length; i++) {
				String name = fields[i].getName(); // 获取属性的名字
				Field f = entity.getClass().getDeclaredField(name);
				String type = fields[i].getGenericType().toString(); // 获取属性的类型
				f.setAccessible(true);
				Object val = f.get(entity);// 得到此属性的值
				if (val == null)
					continue;
				
				//找出实体类属性对于的字段名,如果找不到则忽略此条件
				String columnName = this.getColumeName(entity, name);
				if (StringUtil.isEmpty(columnName)) continue;
				
				
				if (type.equals("class java.lang.String")) {
					String stringValue = val.toString();
					if (!StringUtil.isEmpty(stringValue)) {
						criteria.andCondition(columnName + " = ", stringValue);
					}
				}

				if (type.equals("class java.lang.Integer")) {
					Integer intValue = Integer.valueOf(val.toString());
					criteria.andCondition(columnName + " = ", intValue.intValue());
				}
				
				
				if (type.equals("class java.lang.Short")) {
					Short shortValue = Short.valueOf(val.toString());
					criteria.andCondition(columnName + " = ", shortValue);
				}

				if (type.equals("class java.lang.Long")) {
					Long  longValue = Long.valueOf(val.toString());
					criteria.andCondition(columnName + " = ", longValue);
				}

				if (type.equals("class java.lang.Double")) {
					Double doubleValue = Double.valueOf(val.toString());
					criteria.andCondition(columnName + " = ", doubleValue);
				}

				if (type.equals("class java.lang.BigDecimal")) {
					BigDecimal bValue = new BigDecimal(val.toString());
					criteria.andCondition(columnName + " = ", bValue);
				}

				if (type.equals("class java.util.Date")) {
					Date dateValue = (Date)val;
					criteria.andCondition(columnName + " = ", dateValue);
				}

			}
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 排序
		if (!StringUtil.isEmpty(orderBy)) {
			example.setOrderByClause(orderBy);
		}

		return example;

	}

	public String getColumeName(T entity, String propertyName) {

		Set<EntityColumn> columnList = EntityHelper.getColumns(entity.getClass());

		for (EntityColumn entityColumn : columnList) {
			if (entityColumn.getProperty().equals(propertyName)) {
				return entityColumn.getColumn();
			}
		}
		return "";
	}
}
